import React, { useRef, FC,useImperativeHandle,useState ,forwardRef,useEffect} from 'react'
import { withRouter } from 'react-router-dom'
import MyTable from '@/components/common/table'
import JdApi from '@/api/jd'
import {Button,Input,DatePicker,Modal,Spin,Upload, Table,Form,Steps,Tabs} from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import MySelect from '@/components/common/mySelect'
// import { getQuery } from '@/assets/js/publicFunc'
import { useHistory } from 'react-router-dom'
import {formItemLayout,modalLayoutSm} from '@/config/layout';
import $axios from '@/utils/axios';
import { idText } from 'typescript';
import { file } from '@babel/types';
const { Step } = Steps; 
const { TabPane } = Tabs;
const { RangePicker } = DatePicker;
const FileList: FC = () => {
  // const query = getQuery()
  // const { type } = query

  const tableRef: RefType = useRef()
  const UploadFileActionRef: RefType = useRef()
  const UploadFileActionMoreRef: RefType = useRef()
  
  const UploadFileDetailRef: RefType = useRef()
  const history = useHistory()

  const columns = [
    {
      title: '模板名称',
      dataIndex: 'fname',
    },
    {
      title: '文件名',
      dataIndex: 'fileName',
      
    },
    
    {
      title: '文件大小',
      dataIndex: 'fileSize',
      render:(text,record,index)=>{
        return  (text/1024/1024).toFixed(2)+'Mb'
      }
    },
    {
      title: '状态',
      dataIndex: 'impStatus',
      render:(txt,record,index)=>{
        const statusOBj = ['导入中','导入成功','导入失败','部分导入成功']
        return <div>
          {statusOBj[record['impStatus']]}
        </div>
      }
    },
    {
      title: '更新时间',
      dataIndex: 'importTime',
    },
    {
      title: '操作',
      dataIndex: 'scan',
      render:(text,record,index)=>{
        return <div>
          <Button onClick={()=>{detail(record)}}>详情</Button>
          <Button style={{marginLeft:'10px'}} onClick={()=>{ del(record.id)}}>删除</Button>
         
        </div>
      }
    },
  ]
  // 新增按钮
  const AddBtn = () => (
    <Button className="fr" onClick={add} type="primary">
      导入数据
    </Button>
  )
  // 新增按钮
  const BatchAddBtn = () => (
    <Button style={{marginLeft:'10px'}} className="fr" onClick={BatchAdd} type="default" >
      批量导入
    </Button>
  ) 
    // 删除
  const del = (id) => {
    Modal.confirm({
      title: '确认删除？',
      
      onOk() {
        $axios.delete('/jd/data/data/delete/'+id).then(()=>{
          tableRef.current.update();
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }

  // 添加
  const add = () => { 
    UploadFileActionRef.current.init()
  }
  // 添加
  const BatchAdd = () => { 
    UploadFileActionMoreRef.current.init()
  }
  // 详情
  const detail = (record) => {
    UploadFileDetailRef.current.init(record.id);
  }

  // 搜索栏配置项
  const searchConfigList = [
    {
      key: 'fileName',
      slot: <Input placeholder="请输入关键字" allowClear />,
      rules: [],
      initialValue: ''
    },
  ]
  return (
    <>
      <div>
        {/* <BatchDel /> */}
        <BatchAddBtn />
        <AddBtn />
      </div> 
     
      
      <MyTable
        apiFun={JdApi.getDataList}
        columns={columns}
        ref={tableRef}
        searchConfigList={searchConfigList}
        extraProps={{ results: 10 }}
       
        // onSelectRow={(values)=>{
        //   console.log(values);
        // }}
      />
      <UploadFileActionCom ref={UploadFileActionRef} callback={()=>{
          tableRef.current.update();
        }}/>
        <UploadFileActionMoreCom ref={UploadFileActionMoreRef} callback={()=>{
          tableRef.current.update();
        }}/>


      <UploadFileDetailCom ref={UploadFileDetailRef} callback={()=>{
          tableRef.current.update();
        }}/>


    </>
  )
}


let onProgress1 = null;
//新建/修改
const UploadFileAction = (props,refs) => {
  const [form] = Form.useForm()
  // const [fileList,setfileList] = useState([]);
  const [formdatavalues,setformdata] = useState(null);
  const [fileName,setFileName] = useState('');
  const [isUploading,setUploading] = useState(false);
  const { setFieldsValue } = form
  const [loading, setLoading] = useState<boolean>(false)
  const [temList,setTemList] = useState([]);
  const [fileID,setfileID] = useState('');
  let  handokRequest = null;
  //显示隐藏弹窗
  const [isModalVisible, setIsModalVisible] = useState(false);
  useImperativeHandle(refs, () => ({
    init: (id='') => {
      showModal();
      setFileName('');
      setUploading(false);
      setfileID(id);
      // setfileList([]);
    }
  }))
  const getRoleList = ()=>{
    JdApi.getTemplateList({pageSize:10000}).then((res)=>{
      let list = res['data']['list'];
      list.map((e,i)=>{
        list[i]['name'] = e['tplName'];
        list[i]['key'] = e['id'];
        return 1
      })
      setTemList(list);
    })
  }
  useEffect(()=>{
    getRoleList();
  },[])
  //显示弹窗
  const showModal = () => {
    setIsModalVisible(true);
    setUploading(false);
  };
  //确定
  const handleOk = () => {
    form.validateFields().then((vals) => {
      const Obj = form.getFieldsValue()
      let url = '/jd/data/data/import';
      Obj['importType']=0;
      Obj['sheets'] = [];
      if(fileID){
        url = '/jd/data/data/importdata';
        Obj['fileID'] = fileID;
        Obj['importType']=1;
      }
      let withCredentials = false;
      let headers = {

      }
      let newFormaData = formdatavalues;
      for(let e in Obj){
        // newFormaData.append(e, Obj[e]);
      }
      const keys = Object.keys(Obj)
      url = keys.reduce((pre, cur) => `${pre}${cur}=${Obj[cur]}&`, url + '?')
      url = encodeURI(url.substr(0, url.length - 1))

     
      setLoading(true);



      return $axios
      .post(url, newFormaData, {
        withCredentials,
        headers,
        onUploadProgress: ({ total, loaded }) => {
          console.log(Math.round((loaded / total) * 100).toFixed(2));
        },
      })
      .then(({ data: response }) => {
        setUploading(true);
        setLoading(false);
        handleCancel();
      })
      .catch((err)=>{
        setLoading(false);
      });
     
     
    }).catch(info => {
      
    })
  };
  //取消
  const handleCancel = () => {
    setIsModalVisible(false);
    setLoading(false);
    props.callback&&props.callback();
  };
  const uploadprops = {
    // // 'customRequest':customRequest
    // name: 'file',
    // action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
    // headers: {
    //   authorization: 'authorization-text',
    // },
    action: '/dm/api/v1/common/file/upload',
    multiple: false,
    data: { },
    headers: {
      Authorization: '$prefix $token',
    },
    onStart(file) {
      setFileName(file.name);
      setFieldsValue({
        file:file.name
      })
    },
    onSuccess(res, file) {
      console.log('onSuccess', res, file.name);
    },
    onError(err) {
      console.log('onError', err);
    },
    onProgress({ percent }, file) {
      console.log('onProgress', `${percent}%`, file.name);
    },
    customRequest({
      action,
      data,
      file,
      filename,
      headers,
      onError,
      onProgress,
      onSuccess,
      withCredentials,
    }) {
      onProgress1 = onProgress;
      const formData = new FormData();
      if (data) {
        Object.keys(data).forEach(key => {
          formData.append(key, data[key]);
        });
      }
      formData.append(filename, file);
      setformdata(formData);
      return {
        abort() {
          console.log('upload progress is aborted.');
        },
      };
    }
  };
  
  return <Modal 
    title="导入文件" 
    visible={isModalVisible} 
    onOk={handleOk} 
    onCancel={handleCancel}
    width={650}
    maskClosable={false}
    footer = {
      <div>
        {
          loading?<>
          <Button disabled>取消</Button>
        <Button type="primary" loading={true}>确定</Button></>:<>
          <Button onClick={handleCancel}>取消</Button>
          <Button type="primary" onClick={handleOk}>确定</Button>
        </>
        }
        
      </div>
    }
    >

    <Spin spinning={loading}>
      <Form form={form} {...modalLayoutSm}>
        <Form.Item
          name="fid"
          label="选择模板"
          rules={[
            {
              required: true,
              message: '请选择模板'
            }
          ]}
        > 
          <MySelect data={temList}>

          </MySelect>
        </Form.Item>
        
        <Form.Item
          name="file"
          label="选择文件"
          rules={[
            {
              required: true,
              message: '请选择文件'
            }
          ]}
        > 
          <Upload {...uploadprops} style={{width:'100%'}}  showUploadList={false}>
            <div style={{cursor:'pointer'}}>
              <Input value={fileName} style={{width:'504px',cursor:'pointer'}} className="pointer" disabled addonAfter="浏览" placeholder="选择文件"/>
            </div>
            
          </Upload>
        </Form.Item>
      </Form>
    </Spin>
    
  </Modal>
}
const UploadFileActionCom = forwardRef(UploadFileAction);


//新建/修改
const UploadFileActionMore = (props,refs) => {
  const [form] = Form.useForm()
  // const [fileList,setfileList] = useState([]);
  const [formdatavalues,setformdata] = useState(null);
  const [fileName,setFileName] = useState('');
  const [fileList,setfileList] = useState([]);
  const [isUploading,setUploading] = useState(false);
  const { setFieldsValue } = form
  const [loading, setLoading] = useState<boolean>(false)
  const [temList,setTemList] = useState([]);
  let  handokRequest = null;
  //显示隐藏弹窗
  const [isModalVisible, setIsModalVisible] = useState(false);
  useImperativeHandle(refs, () => ({
    init: (id) => {
      showModal();
      setfileList([])
      setFileName('');
      setUploading(false);
      // setfileList([]);
    }
  }))
  const getRoleList = ()=>{
    JdApi.getTemplateList({pageSize:10000}).then((res)=>{
      let list = res['data']['list'];
      list.map((e,i)=>{
        list[i]['name'] = e['tplName'];
        list[i]['key'] = e['id'];
        return 1
      })
      setTemList(list);
    })
  }
  useEffect(()=>{
    getRoleList();
  },[])
  //显示弹窗
  const showModal = () => {
    setIsModalVisible(true);
    setUploading(false);
  };
  //确定
  const handleOk = () => {
    form.validateFields().then((vals) => {


      const Obj = form.getFieldsValue()
      let url = '/jd/data/data/import';
      Obj['importType']=0;
      Obj['sheets'] = [];

      let withCredentials = false;
      let headers = {

      }
      for(let e in Obj){
        // newFormaData.append(e, Obj[e]);
      }
      const keys = Object.keys(Obj)
      url = keys.reduce((pre, cur) => `${pre}${cur}=${Obj[cur]}&`, url + '?')
      url = encodeURI(url.substr(0, url.length - 1))
      setLoading(true);
       //我给的
       let finishedCount = 0;
       let completeArr = [];
       let failArr = [];
        const completeFn = (isSuccess,index)=>{

          if(isSuccess){
            completeArr.push(index);
          }else{
            failArr.push(fileList[index]);
          }
          finishedCount = finishedCount+1;
          if(finishedCount==fileList.length){
            setLoading(false);
            console.log(completeArr);
            console.log(failArr);
            
            if(completeArr.length==fileList.length){
              setUploading(true);
              handleCancel(); 
            }else{
              setfileList(failArr);
            }
           
          }
        };
       fileList.map((e,i)=>{
        let newFormaData = new FormData();
         newFormaData.append('file',e['file']);
         $axios
         .post(url, newFormaData, {
           withCredentials,
           headers,
           onUploadProgress: ({ total, loaded }) => {
             console.log(Math.round((loaded / total) * 100).toFixed(2));
           },
         })
         .then(({ data: response }) => {
            
            completeFn(true,i);
         })
         .catch((err)=>{
            completeFn(false,i);
         });
       })
      







     
    })

  };
  
  //取消
  const handleCancel = () => {
    setIsModalVisible(false);
    setLoading(false);
    setfileList([])
    props.callback&&props.callback();
  };
  const uploadprops = {
    // // 'customRequest':customRequest
    // name: 'file',
    // action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
    // headers: {
    //   authorization: 'authorization-text',
    // },
    action: '/dm/api/v1/common/file/upload',
    multiple: true,
    data: { },
    headers: {
      Authorization: '$prefix $token',
    },
    fileList:fileList,
    onStart(file) {
      setFileName(file.name);
      setFieldsValue({
        file:file.name
      })
    },
    onSuccess(res, file) {
      console.log('onSuccess', res, file.name);
    },
    onError(err) {
      console.log('onError', err);
    },
    onProgress({ percent }, file) {
      console.log('onProgress', `${percent}%`, file.name);
    },
    showUploadList: {
      showDownloadIcon: true,
      downloadIcon: 'download ',
      showRemoveIcon: true,
      removeIcon: 'del',
    },
    onRemove:(file)=>{
      let newfileList = fileList.concat([]);
      let newfileListObj = {};
      newfileList.map((e,i)=>{
        newfileListObj[e['uid']] = e;
      })
      delete newfileListObj[file['uid']];
      newfileList = [];
      for(let i in newfileListObj){
        newfileList.push(newfileListObj[i]);
      }
      setfileList(newfileList);
      return true;
    },
    customRequest({
      action,
      data,
      file,
      filename,
      headers,
      onError,
      onProgress,
      onSuccess,
      withCredentials,
    }) {
      onProgress1 = onProgress;
      const formData = new FormData();
      // if (data) {
      //   Object.keys(data).forEach(key => {
      //     formData.append(key, data[key]);
      //   });
      // }
      // formData.append(filename, file);
      setfileList(fileList.concat({
        name:file.name,
        file:file,
        uid:Math.random()+''
      }))
      // setformdata(formData);
      return {
        abort() {
          console.log('upload progress is aborted.');
        },
      };
    }
  };
  
  return <Modal 
    title="批量导入文件" 
    visible={isModalVisible} 
    onOk={handleOk} 
    onCancel={handleCancel}
    width={650}
    maskClosable={false}
    footer = {
      <div>
        {
          loading?<>
          <Button disabled>取消</Button>
        <Button type="primary" loading={true}>确定</Button></>:<>
          <Button onClick={handleCancel}>取消</Button>
          <Button type="primary" onClick={handleOk}>确定</Button>
        </>
        }
        
      </div>
    }
    >

    <Spin spinning={loading}>
      <Form form={form} {...modalLayoutSm}>
        <Form.Item
          name="fid"
          label="选择模板"
          rules={[
            {
              required: true,
              message: '请选择模板'
            }
          ]}
        > 
          <MySelect data={temList}>

          </MySelect>
        </Form.Item>
        <Form.Item
          name="file"
          label="选择文件"
          rules={[
            {
              required: true,
              message: '请选择文件'
            }
          ]}
        > 
          <Upload {...uploadprops} style={{width:'100%'}}  showUploadList={true}>
            <Button>增加文件</Button>
          </Upload>
         
        </Form.Item>
      </Form>
    </Spin>
    
  </Modal>
}
const UploadFileActionMoreCom = forwardRef(UploadFileActionMore);


const UploadFileDetail = (props,refs) => {
  //显示隐藏弹窗
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [id,setId] = useState('');

  //sheet页
  const [sheetList,setSheetList] = useState([]);
  const [activeKey,setactiveKey] = useState('0');

  //加载中
  const [loading, setLoading] = useState<boolean>(false)


  //表格数据
  const [tableData,setTableData] = useState([]);
  const [maxColNum,setMaxColNum] = useState(0);
  const [tableShow,setTableShow] = useState(false);
  useImperativeHandle(refs, () => ({
    init: (id) => {
      setId(id);
      getDetail(id);
      showModal();
    }
  }))

  //获取文件详情
  const getDetail = (qid)=>{
    setLoading(true);
    let query_id = qid?qid:id
    JdApi.getDataInfo(query_id).then((res)=>{
      let newSheetList = res['data']['sheetList']?res['data']['sheetList']:[];
      setLoading(false);
      setSheetList(newSheetList);
      handleSheetData(res['data']);
    })
  }
  //获取文件sheet详情
  const getSheetDetail = (index:string)=>{
    setLoading(true);
    JdApi.getDataSheetInfo(id,index).then((res)=>{
      handleSheetData(res['data']);
      setLoading(false);
    })
  }
  //处理表格数据
  const handleSheetData = (data)=>{
    setTableShow(false);
    let cellMerge:Array<object> = data['cellMerge']?data['cellMerge']:[];
    let table:Array<object> = data['table']?data['table']:[];
    let cellMergeObj = {};
    let tableObj = {};
    let maxCol = 0;
    let dataArr = [];
    cellMerge.map((e,i)=>{
     
      let firstRow = e['firstRow'];
      let firstColumn = e['firstColumn'];
      let lastRow = e['lastRow'];
      let lastColumn = e['lastColumn'];
      if(!cellMergeObj[firstRow]){
        cellMergeObj[firstRow]={

        }
      }
      cellMergeObj[firstRow][firstColumn]={
        "colSpan": lastColumn-firstColumn+1,
        "rowSpan": lastRow-firstRow+1
      }

    })
    table.map((e,i)=>{
      let rowIdx = e['rowIdx'];
      let colIdx = e['colIdx'];
      if(!tableObj[rowIdx]){
        tableObj[rowIdx]={

        }
      }
      if(maxCol<colIdx){
        maxCol = colIdx;
      }
      tableObj[rowIdx][colIdx] = e;
    })

    for(let i in tableObj){
      let item = {
        "key": i,
        // "A": {
        //   "name": "A",
        //   "colSpan": 1,
        //    "rowSpan":3
        // },
        // "B": {
        //   "name": "B",
        //   "colSpan": 4
        // }
      }
      let tableitem = tableObj[i];
      for(let j in  tableitem){
        if(cellMergeObj[i]&&cellMergeObj[i][j]){
          item[rowKeys[j]] = {
            ...tableitem[j],
            "colSpan": cellMergeObj[i][j]['colSpan'],
            "rowSpan": cellMergeObj[i][j]['rowSpan']
          }
        }else{
          item[rowKeys[j]] = {
            ...tableitem[j],
            "colSpan": 1,
            "rowSpan": 1
          }
        }
        
      }
      dataArr.push(item);
    }
    setMaxColNum(maxCol);
    setTableData(dataArr);
    setTableShow(true);
  }
  //显示弹窗
  const showModal = () => {
    setIsModalVisible(true);
  };
   //取消
  const handleCancel = () => {
    setIsModalVisible(false);
    setSheetList([]);
    setactiveKey('0');
    props.callback&&props.callback();
  };
  // sheet改变
  const sheetChange = (key)=>{
    setactiveKey(key);
   
    getSheetDetail(key+'')
  }
  return <Modal 
    title="详情" 
    visible={isModalVisible} 
    onCancel={handleCancel}
    width={window.innerWidth-100}
    centered={true}
    bodyStyle={{
      height:window.innerHeight-250
    }}
    footer={
      <>
        <Button onClick={handleCancel}>关闭</Button>
      </>
    }>
      <Spin spinning={loading}>
        <Tabs type="card" activeKey={activeKey} onChange={sheetChange} tabPosition="bottom">
          {
            sheetList.map((e,i)=>{
              return <TabPane tab={e['sheetName']} key={i+''}>
                  {
                    tableShow&& <TemplateTable maxColNum={maxColNum} data={tableData} />
                  }
                 
                </TabPane>
            })
          }
        </Tabs>
      </Spin>
      
  </Modal>
}

const UploadFileDetailCom = forwardRef(UploadFileDetail);

export default withRouter(FileList)
interface TemplateTableProps {
  data?:object[],
  maxColNum?:number
}

const TemplateTable: FC<TemplateTableProps> = (prop:TemplateTableProps) => {
  const columns = [
   
  ];
  columns.push({
    title:'',
    dataIndex:'index',
    key:'index',
    width:'20px',
    fixed:'left',
    render:(txt,record,index)=>{
       return index+1
    } 
  });
  let maxCol = 100000;
  let renderRowKey = rowKeys.concat([]);
  renderRowKey = renderRowKey.splice(0,maxCol);
  renderRowKey.map((e,i)=>{
    let column = {
      title:e,
      dataIndex:e,
      key:e,
      colSpan:1,
      // width:'80px',
      render:(value,record,index)=>{
        let values = record[e]?record[e]:{};
        let obj = {};
        if(values['colSpan']){
          obj = {
            children: <div style={{minWidth:'40px'}}>
              {record[e].dataContent}
            </div>,
            props: {
              colSpan:values['colSpan']?values['colSpan']:0,
              // rowSpan:values['rowSpan']?values['rowSpan']:0
            },
          };
        }else{
          obj = {
            props: {
              colSpan:0
            },
          };
          
        }
        if(values['rowSpan']){
          obj['props']['rowSpan'] = values['rowSpan'];
        }
        return obj
      }
    };
    columns.push(column)
  })
  console.log(prop['data']);
  
  return <>
    <Table bordered={true} pagination={false} columns={columns} dataSource={prop['data']} scroll={{ x: 'max-content', y: window.innerHeight-400 }} />
  </>
}
const alphabet = ['','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
const alphabet1 = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
const rowKeys = [];
alphabet.map((e)=>{
  alphabet1.map((k)=>{
    rowKeys.push(e+k);
  })
})


